package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Question;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.MyThreadLocal;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@Service
public class TanhuaService {
    //指定默认数据
    @Value("${tanhua.default.recommend.users}")
    private String recommendUser;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate template;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MessagesService messagesService;

    @DubboReference
    private UserLocationApi userLocationApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    //今日佳人
    public TodayBest todayBest() {
        Long userId = MyThreadLocal.getUserId();

        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);

        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }

        UserInfo userInfo = userInfoApi.getById(recommendUser.getUserId());

        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);

        return todayBest;
    }

    //分页查询推荐好友列表
    public PageResult recommendation(RecommendUserDto dto) {
        Long userId = MyThreadLocal.getUserId();
        //调用recommendUserApi分页查询数据列表
        PageResult pr = recommendUserApi.queryRecommendUserList(dto.getPage(), dto.getPagesize(), userId);
        //获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();

        if (CollUtil.isEmpty(items)) {
            return pr;
        }
        //提取所有推荐的用户id列表
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());


        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);


        ArrayList<TodayBest> list = new ArrayList<>();

        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info != null) {
                TodayBest todayBest = TodayBest.init(info, item);
                list.add(todayBest);
            }
        }
        pr.setItems(list);
        return pr;
    }

    //查询佳人信息
    public TodayBest personalInfo(Long userId) {
        UserInfo userInfo = userInfoApi.getById(userId);

        RecommendUser user = recommendUserApi.queryByUserId(MyThreadLocal.getUserId(), userId);

        //构造访客数据
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);
        visitors.setVisitorUserId(MyThreadLocal.getUserId());
        visitors.setScore(user.getScore());
        visitors.setFrom("首页");
        visitors.setDate(System.currentTimeMillis());
        visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        visitorsApi.save(visitors);


        return TodayBest.init(userInfo, user);
    }

    //查询陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.getById(userId);
        return question == null ? "你喜欢java编程吗？" : question.getTxt();

    }

    //回复陌生人问题
    public void replyQuestions(Long userId, String reply) {
        Long currentUserId = MyThreadLocal.getUserId();
        UserInfo userInfo = userInfoApi.getById(currentUserId);
        //构造消息数据
        Map map = new HashMap();
        map.put("userId", currentUserId);
        map.put("huanXinId", Constants.HX_USER_PREFIX + currentUserId);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", strangerQuestions(userId));
        map.put("reply", reply);
        String message = JSON.toJSONString(map);

        Boolean aBoolean = template.sendMsg(Constants.HX_USER_PREFIX + userId, message);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    //探花-推荐用户列表
    public List<TodayBest> queryCardsList() {
        //1、调用推荐API查询数据列表（排除喜欢/不喜欢的用户，数量限制）
        List<RecommendUser> users = recommendUserApi.queryCardsList(MyThreadLocal.getUserId(), 10);
        //2、判断数据是否存在，如果不存在，构造默认数据 1,2,3
        if (CollUtil.isEmpty(users)) {
            users = new ArrayList<>();
            String[] userIdS = recommendUser.split(",");
            for (String userId : userIdS) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(MyThreadLocal.getUserId());
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                users.add(recommendUser);
            }
        }

        //3、构造VO
        List<Long> ids = CollUtil.getFieldValues(users, "userId", Long.class);
        Map<Long, UserInfo> infoMap = userInfoApi.findByIds(ids, null);

        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : users) {
            UserInfo userInfo = infoMap.get(user.getUserId());
            if (userInfo != null) {
                TodayBest vo = TodayBest.init(userInfo, user);
                vos.add(vo);
            }
        }
        return vos;
    }

    //左滑喜欢
    public void likeUser(Long likeUserId) {
        //保存喜欢数据
        Boolean save = userLikeApi.saveOrUpdate(MyThreadLocal.getUserId(), likeUserId, true);
        if (!save) {
            throw new BusinessException(ErrorResult.error());
        }
        //、操作redis，写入喜欢的数据，删除不喜欢的数据
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + MyThreadLocal.getUserId(), likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + MyThreadLocal.getUserId(), likeUserId.toString());

        if (isLike(MyThreadLocal.getUserId(), likeUserId)) {
            messagesService.contacts(likeUserId);
        }

    }

    //右滑不喜欢
    public void notLikeUser(Long likeUserId) {
        Boolean save = userLikeApi.saveOrUpdate(MyThreadLocal.getUserId(), likeUserId, false);
        if (!save) {
            throw new BusinessException(ErrorResult.error());
        }
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY + MyThreadLocal.getUserId(), likeUserId.toString());
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + MyThreadLocal.getUserId(), likeUserId.toString());

        if (isLike(MyThreadLocal.getUserId(), likeUserId)) {
            messagesService.removeContacts(likeUserId);
        }

    }

    //判断是否双向喜欢
    public Boolean isLike(Long userId, Long likeUserId) {
        String key = Constants.USER_LIKE_KEY + userId;
        return redisTemplate.opsForSet().isMember(key, likeUserId.toString());
    }

    //搜附近
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //调用API查询附近的用户（返回的是附近的人的所有用户id，包含当前用户的id）
        List<Long> userIds = userLocationApi.queryNearUser(MyThreadLocal.getUserId(), Double.valueOf(distance));
        if (CollUtil.isEmpty(userIds)) {
            return new ArrayList<>();
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setGender(gender);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);

        ArrayList<NearUserVo> vos = new ArrayList<>();
        for (Long userId : userIds) {
            if (userId == MyThreadLocal.getUserId()) {
                continue;
            }
            UserInfo info = map.get(userId);
            if (info != null) {
                NearUserVo vo = NearUserVo.init(info);
                vos.add(vo);
            }
        }
        return vos;
    }
}
